﻿using System;
using System.Collections.Generic;
using System.Data;
using CoreSoft.Frame.Entity;
using CoreSoft.Frame.Entity.http;
using FERROU8API.Pub;
using U8Login;
using UFIDA.U8.MomServiceCommon;
using UFSoft.U8.Framework.ContextSrv;
using UFSoft.U8.Framework.DBConnection;

namespace FERROU8API.Plugin
{
    /// <summary>
    /// 生产订单
    /// </summary>
    public class MoorderPlugin
    {
        //private readonly string _ip = ConfigurationManager.AppSettings["WmsIP"] + "Moorderapi";
        public static string constr = "";
        private string url = "";




        public static string getSyncDbConnection(string server, string user, string psd, string db)
        {
            return "Server = " + server + ";User = " + user + "; Pwd = " + psd + ";Database = " + db;
        }

        public bool Update_After(ref int moid, ref int modid, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            try
            {
                DebugWriteLog.WriteLine("MoorderPlugin", "Update_After", "进入");
                U8LoginInfo info = UFSoft.U8.Framework.ContextSrv.UserContextGetter.U8LoginInfo;
                UFSoft.U8.Framework.DBConnection.ConnectionCourier conier = UFSoft.U8.Framework.DBConnection.ConnectionCourier.Instance;
                constr = conier.GetCurrentConnection().ConnectionString;
                if (string.IsNullOrEmpty(constr))
                {
                    errMsg = "MoorderPlugin，Update_After，获取连接串失败";
                    DebugWriteLog.WriteLine("MoorderPlugin", "Update_After", errMsg);
                    return false;
                }
                string accid = info.UserAccountId;

                //MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;
                //clsLogin login = ctx.U8Login as clsLogin;
                //if (login != null)
                //    constr = login.UFDataConnstringForNet;

                String js;

                js = GetCustJs(accid, moid, modid, 0, 1);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }
                DebugWriteLog.WriteLine("MoorderPlugin", "url", url);
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                DebugWriteLog.WriteLine("MoorderPlugin", "Update_After", apiresult.ToJson());
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    DebugWriteLog.WriteLine("MoorderPlugin", "Update_After", errMsg);
                    return false;
                }

                return true;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("MoorderPlugin", "Update_After", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }

       


        private string GetCustJs(string accid, int moid, int modid, int operation, int key)
        {
            DebugWriteLog.WriteLine("生产订单接口", "moid", "moid=" + Convert.ToString(moid) + ";modid=" + Convert.ToString(modid));

            try
            {
                var datatable = Common.GetUrl(constr, accid).Tables[0];
                if (datatable == null)
                {
                    DebugWriteLog.WriteLine("生产订单接口", "GetUrl", "Nopermission");
                    return "Nopermission";
                }
                var datarow = datatable.Rows[0];
                if (datatable == null)
                {
                    DebugWriteLog.WriteLine("生产订单接口", "GetUrl", "datarow Nopermission");
                    return "Nopermission";
                }
                url = datarow[1] + "productionOrder/";

                string sqlhead = "select MoCode,CreateDate,CreateUser,CreateTime from mom_order with(nolock) where moid = '" + moid + "'";
                var headtable = DbHelperSQL.Query(sqlhead, constr, null).Tables[0];
                if (headtable == null)
                {
                    DebugWriteLog.WriteLine("生产订单接口", "headtable", " Nopermission");
                    return "Nopermission";
                }
                #region SQL代码片段

                //inv.cInvStd 成品规格
                string sql = @"select DISTINCT
                            b.MoDId,b.MoId,b.SortSeq,b.InvCode,b.Qty,b.Status,b.CustCode,b.OrgClsDate,b.CloseDate,b.RelsUser,b.RelsDate,
                            b.MrpQty,b.Free1,b.Free2,b.Free3,b.Free4,b.Free5,b.Free6,b.Free7,b.Free8,b.Free9,b.Free10,
                            b.WhCode,b.OrderCode,b.OrderSeq,b.OrderDId,
                            a.createdate, a.CreateUser,a.ModifyUser,b.MDeptCode,
                            c.startdate,
                            c.duedate, 
                            f.dPreDate,
                            b.SoCode, 
                            isnull(e.ccuscode, mps.CustCode) as ccuscode,
                            g.motypecode,
                            b.Define30,
                            b.OrderCode,
                            h.cbdefine3,
                            b.define29,
                            b.MDeptCode as whocode
                            from  mom_orderdetail b 	
                            left join mom_orderdetail_extradefine h on h.MoDId = b.MoDId 
                            left join mom_morder c on c.MoDId=b.MoDId
						    left join mom_order a on b.moid=a.MoId
                            left join so_somain e on e.csocode=b.socode
							left join so_sodetails f on f.id = e.id and f.cinvcode = b.invcode
                            left join mom_motype g ON g.motypeid =b.motypeid
                            left join Inventory inv on b.InvCode=inv.cInvCode
                            left join mps_forecastdetail mps on mps.DemandCode = b.DemandCode 
                            left join mps_forecast mp on mp.ForecastId = mps.ForecastId
                            where b.modid= '" + modid + "'";
                DebugWriteLog.WriteLine("生产订单接口", "GetCustJ - SQL:", sql);

                var table = DbHelperSQL.Query(sql, constr, null).Tables[0];
                if (table == null)
                {
                    DebugWriteLog.WriteLine("生产订单接口", "table", " Nopermission");
                    return "Nopermission";
                }
                //DebugWriteLog.WriteLine("Status:" + table.Rows[0]["Status"]);

                //if (table.Rows[0]["Status"].ToString() == "0") //开立状态
                //{
                //    return "Nopermission";
                //}


                string modids = string.Empty;

                List<DataItem> mlist = new List<DataItem>();
                foreach (DataRow item in table.Rows)
                {
                    string define29 = item["define29"].ObjToString();
                    if (define29.ToUpper().Equals("N"))
                    {
                        return "Nopermission";
                    }
                    modids += item["MoDId"] + ",";

                    #region mes原有字段
                    DataItem mesOrder = new DataItem();
                    mesOrder.LineId = headtable.Rows[0]["MoCode"].ObjToString(); //MoCode 生产订单号码  
                    mesOrder.Reserved1 = item["SortSeq"].ObjToString(); //SortSeq 行号  
                    mesOrder.DocStatus = item["Status"].ObjToString(); //Status 状态（NA-开立/FM-锁定/OP-审核/CL-关闭） 
                    mesOrder.MainQty = item["Qty"].ObjToDecimal(); //Qty 生产订单数量  
                    mesOrder.PartName = item["InvCode"].ObjToString(); //InvCode 存货编码  
                    mesOrder.CustomerPartId = item["ccuscode"].ObjToString(); //客户代号
                    //mesOrder.PlanEndDate = item["OrgClsDate"].ObjToDate();//OrgClsDate 原始结案日期 //计划完成日期
                    mesOrder.CreatedUser = headtable.Rows[0]["CreateUser"].ObjToString();  //创建人

                    mesOrder.ApprovedUser = item["RelsUser"].ObjToString(); // 审核人
                    mesOrder.ApprovedDate = DateTime.Now.Date.ToString("yyyy-MM-dd"); // 审核日期 
                    //mesOrder.MoDId = item["MoDId"].ObjToString(); //MoDId 生产订单明细资料ID
                    #endregion

                    #region 新加字段-2017-11-7-plf
                    mesOrder.CustomerCode = string.IsNullOrEmpty(item["ccuscode"].ObjToString()) ? "EGEWG" : item["ccuscode"].ObjToString(); //客户编号
                    mesOrder.ScheduleDate = item["createdate"].ObjToDate().AddDays(1).ToString("yyyy-MM-dd hh:mm:ss"); //订单日期 
                    mesOrder.CreatedDate = headtable.Rows[0]["CreateDate"].ObjToDate().ToString("yyyy-MM-dd hh:mm:ss");  //创建日期
                    mesOrder.PlanStartDate = item["startdate"].ObjToDate().ToString("yyyy-MM-dd hh:mm:ss"); //计划开工日期 
                    mesOrder.PlanEndDate = item["duedate"].ObjToDate().ToString("yyyy-MM-dd hh:mm:ss"); //计划完工工日期 
                    mesOrder.RequireDate = item["dPreDate"].ObjToDate().ToString("yyyy-MM-dd hh:mm:ss"); //交货日期 --预发货日期 （u8）
                    mesOrder.SubQty = item["MrpQty"].ObjToDecimal(); //MrpQty Mrp净算量 
                    mesOrder.CustomerOrder = item["SoCode"].ObjToString(); //销售订单号(mes)--来源订单号(erp) 
                    mesOrder.Reserved2 = item["motypecode"].ObjToString(); //类型
                    mesOrder.MDeptCode = item["MDeptCode"].ObjToString();//生产订单部门//yjh新增20240402

                    //mesOrder.PartName = item["partid"].ObjToString();  //物料编号
                    #endregion

                    #region 新增自由项 jifeng
                    //mesOrder.Free1 = item["Free1"].ToString();
                    //mesOrder.Free2 = item["Free2"].ToString();
                    //mesOrder.Free3 = item["Free3"].ToString();
                    //mesOrder.Free4 = item["Free4"].ToString();
                    //mesOrder.Free5 = item["Free5"].ToString();
                    //mesOrder.Free6 = item["Free6"].ToString();
                    //mesOrder.Free7 = item["Free7"].ToString();
                    //mesOrder.Free8 = item["Free8"].ToString();
                    //mesOrder.Free9 = item["Free9"].ToString();
                    //mesOrder.Free10 = item["Free10"].ToString();


                    //mesOrder.Define30 = item["Define30"].ToString();//qz最终客户
                    //mesOrder.WhoCode = item["WhCode"].ToString();//欲入仓库
                    //mesOrder.OrderCode = item["OrderCode"].ToString();
                    //mesOrder.OrderSeq = item["OrderSeq"].ObjToInt32();
                    //mesOrder.OrderDId = item["OrderDId"].ObjToInt32();
                    mesOrder.IsAutoInWh = "0";
                    #endregion

                    #region 新增字段 fulj 20180301
                    mesOrder.Define30 = item["Define30"].ObjToString();     //最终客户
                    mesOrder.OrderCode = item["OrderCode"].ObjToString();   //销售订单号
                    mesOrder.Cbdefine3 = item["cbdefine3"].ObjToString();   //客户最终订单号
                    // 20220303 增加销售订单行号
                    mesOrder.OrderSeq = item["OrderSeq"].ObjToString();
                    #endregion
                #endregion
                    //子件信息
                    List<WorkOrderBomLinesItem> listBomLine = new List<WorkOrderBomLinesItem>();

                    DataTable dtBom = GetMoBom(item["MoDId"].ObjToInt32(), constr, accid);
                    if (dtBom != null && dtBom.Rows.Count > 0)
                    {
                        for (int i = 0; i < dtBom.Rows.Count; i++)
                        {
                            WorkOrderBomLinesItem BomLine = new WorkOrderBomLinesItem();
                            BomLine.BomRrn = dtBom.Rows[i]["AllocateId"].ObjToInt32();  //子件pk
                            BomLine.InvCode = dtBom.Rows[i]["InvCode"].ToString();      //物料编码
                            BomLine.LineMaxQty = dtBom.Rows[i]["Qty"].ObjToDecimal();   //需求数量
                            BomLine.UnitQty = dtBom.Rows[i]["Qtyb"].ObjToDecimal();    //单件用量
                            BomLine.StepName = dtBom.Rows[i]["OpCode"].ToString();       //工序编码
                            BomLine.MaterialSpec1 = dtBom.Rows[i]["cInvStd"].ObjToString(); //规格
                            BomLine.ProductType = dtBom.Rows[i]["ProductType"].ObjToInt32(); //产出类型(1:空/2:联产品/3:副产品)  
                            BomLine.Position = string.IsNullOrEmpty(dtBom.Rows[i]["Define22"].ObjToString()) ? "外层1" : dtBom.Rows[i]["Define22"].ObjToString();  // 位置信息
                            //BomLine.ByproductFlag = dtBom.Rows[i]["ByproductFlag"].ObjToInt32(); //是否联副产品 
                            BomLine.LotNo = dtBom.Rows[i]["LotNo"].ObjToString();
                            listBomLine.Add(BomLine);
                        }
                    }
                    else
                    {
                        DebugWriteLog.WriteLine("生产订单接口", "table", " 子件没有主材");
                        throw new Exception("子件没有主材");
                    }
                    mesOrder.WorkOrderBomLines = listBomLine;
                    //DebugWriteLog.WriteLine("生产订单子件接口", "获取子件ID", listBomLine.ToJson());


                    mlist.Add(mesOrder);
                }

                //DebugWriteLog.WriteLine("生产订单接口", "获取订单表", mlist.ToJson());

                modids = modids.TrimEnd(',');

                #region 子件信息
                // inv.cInvStd 子件规格 
                //                    var sqlzj = @"select d.AllocateId, d.MoDId,mo.MoCode,momd.SortSeq,d.SortSeq,d.OpSeq,d.Qty,d.ComponentId,d.InvCode,
                //                                   d.Free1,d.Free2,d.Free3, d.BaseQtyN, d.BaseQtyD,op.OpCode,
                //                                   inv.cInvStd
                //                                   from mom_moallocate d
                //                                   left join mom_orderdetail momd on d.MoDId=momd.MoDId
                //                                   left join (
                //                                   select prp.PartId,prd.OpSeq,prd.OperationId  from sfc_proutingpart prp 
                //                                   inner join sfc_proutingdetail prd on prd.PRoutingId=prp.PRoutingId )  h on momd.PartId=h.PartId  and d.OpSeq=h.OpSeq
                //                                   left join sfc_operation op on h.OperationId=op.OperationId
                //							       left join mom_order mo on mo.MoId=momd.MoId
                //
                //                                   left join Inventory inv on d.InvCode=inv.cInvCode
                //                                   where d.MoDId in (" + modids + ")";

                //                    var tablezj = DbHelperSQL.Query(sqlzj, constr, null).Tables[0];

                List<MesMoallocate> listmm = new List<MesMoallocate>();

                //foreach (DataRow item in tablezj.Rows)
                //{
                //    MesMoallocate obj = new MesMoallocate();
                //    obj.AllocateId = item["AllocateId"].ObjToInt32();
                //    obj.MoDId = item["MoDId"].ObjToInt32();
                //    obj.SortSeq = item["SortSeq"].ObjToInt32();
                //    obj.OpSeq = item["OpSeq"].ObjToString();
                //    obj.InvCode = item["InvCode"].ToString();
                //    obj.Qty = item["Qty"].ObjToDecimal();
                //    obj.BaseQtyN = item["BaseQtyN"].ObjToDecimal();
                //    obj.BaseQtyD = item["BaseQtyD"].ObjToDecimal();
                //    obj.StepName = item["OpCode"].ObjToString(); //工段-2017-11-19-plf
                //    obj.MaterialSpec1 = item["cInvStd"].ObjToString(); //子件规格-2017-12-01-plf

                //    listmm.Add(obj);

                //}
                #endregion

                //WmsOrder endOrder = new WmsOrder();
                //endOrder.MesOrders = mlist;
                //endOrder.MesMoallocates = listmm;

                ApiRequest req = new ApiRequest();
                req.data = mlist;
                //req.orgcode = login.get_cAcc_Id();
                req.orgcode = accid;
                req.primarykey = key.ToString();
                req.operation = operation;

                DebugWriteLog.WriteLine("生产订单接口", "抛出参数", req.ToJson());
                return req.ToJson();
            }
            catch (Exception e)
            {
                throw e;
            }
        }


        private string GetCustJs_sh(string accid, int moid, int modid, int operation, int key)
        {
            DebugWriteLog.WriteLine("生产订单接口", "moid", "moid=" + Convert.ToString(moid) + ";modid=" + Convert.ToString(modid));

            try
            {
                var datatable = Common.GetUrl(constr, accid).Tables[0];
                if (datatable == null)
                {
                    DebugWriteLog.WriteLine("生产订单接口", "GetUrl", "Nopermission");
                    return "Nopermission";
                }
                var datarow = datatable.Rows[0];
                if (datatable == null)
                {
                    DebugWriteLog.WriteLine("生产订单接口", "GetUrl", "datarow Nopermission");
                    return "Nopermission";
                }
                url = datarow[1] + "productionOrder/";

                string sqlhead = "select MoCode,CreateDate,CreateUser,CreateTime from mom_order with(nolock) where moid = '" + moid + "'";
                var headtable = DbHelperSQL.Query(sqlhead, constr, null).Tables[0];
                if (headtable == null)
                {
                    DebugWriteLog.WriteLine("生产订单接口", "headtable", " Nopermission");
                    return "Nopermission";
                }
                #region SQL代码片段

                //inv.cInvStd 成品规格
                string sql = @"select DISTINCT
                            b.moclass, b.MoDId,b.MoId,b.SortSeq,b.InvCode,b.Qty,b.Status,b.CustCode,b.OrgClsDate,b.CloseDate,b.RelsUser,b.RelsDate,
                            b.MrpQty,b.Free1,b.Free2,b.Free3,b.Free4,b.Free5,b.Free6,b.Free7,b.Free8,b.Free9,b.Free10,
                            b.WhCode,b.OrderCode,b.OrderSeq,b.OrderDId,
                            a.createdate, a.CreateUser,a.ModifyUser,
                            c.startdate,
                            c.duedate, 
                            f.dPreDate,
                            b.SoCode, 
                            e.ccuscode, 
                            g.motypecode,
                            b.define29,
                            b.Define30,
                            b.OrderCode,
                            h.cbdefine3,
                            b.WhCode as whocode
                            from  mom_orderdetail b 	
                            left join mom_orderdetail_extradefine h on h.MoDId = b.MoDId 
                            left join mom_morder c on c.MoDId=b.MoDId
						    left join mom_order a on b.moid=a.MoId
                            left join so_sodetails f on f.iSOsID=b.OrderDId
                            left join so_somain e on e.ID=f.ID	
                            left join mom_motype g ON g.motypeid =b.motypeid
                            left join Inventory inv on b.InvCode=inv.cInvCode
                            where b.modid= '" + modid + "' and ISNULL(b.define29,'') != 'N'";

                var table = DbHelperSQL.Query(sql, constr, null).Tables[0];
                if (table == null)
                {
                    DebugWriteLog.WriteLine("生产订单接口", "table", " Nopermission");
                    return "Nopermission";
                }

                string modids = string.Empty;

                List<DataItem> mlist = new List<DataItem>();
                foreach (DataRow item in table.Rows)
                {
                    //string define29 = item["define29"].ObjToString();
                    //if (define29.ToUpper().Equals("N"))
                    //{
                    //    return "Nopermission";
                    //}
                    modids += item["MoDId"] + ",";

                    #region mes原有字段
                    //add by fulj 2021-11-11增加按订单类型 标准-非标准判断子件是否维护了相关材料 于标准订单 存货分类01,06,08,09， 非标准订单，检查存货分类只有06,07
                    bool bmoa = this.checkMoabyMoclass(item["MoDId"].ObjToString(), item["moclass"].ObjToString(), constr);
                    if (!bmoa)
                    {
                        DebugWriteLog.WriteLine("生产订单接口", "table", item["SortSeq"].ObjToString() + "行,子件没有主材,请检查");
                        throw new Exception(item["SortSeq"].ObjToString() + "行,子件没有主材,请检查");
                    }

                    DataItem mesOrder = new DataItem();
                    mesOrder.LineId = headtable.Rows[0]["MoCode"].ObjToString(); //MoCode 生产订单号码  
                    mesOrder.Reserved1 = item["SortSeq"].ObjToString(); //SortSeq 行号  
                    mesOrder.DocStatus = item["Status"].ObjToString(); //Status 状态（NA-开立/FM-锁定/OP-审核/CL-关闭） 
                    mesOrder.MainQty = item["Qty"].ObjToDecimal(); //Qty 生产订单数量  
                    mesOrder.PartName = item["InvCode"].ObjToString(); //InvCode 存货编码  
                    mesOrder.CustomerPartId = item["CustCode"].ObjToString(); //客户代号
                    //mesOrder.PlanEndDate = item["OrgClsDate"].ObjToDate();//OrgClsDate 原始结案日期 //计划完成日期
                    mesOrder.CreatedUser = headtable.Rows[0]["CreateUser"].ObjToString();  //创建人

                    mesOrder.ApprovedUser = item["RelsUser"].ObjToString(); // 审核人
                    mesOrder.ApprovedDate = DateTime.Now.Date.ToString("yyyy-MM-dd"); // 审核日期 
                    //mesOrder.MoDId = item["MoDId"].ObjToString(); //MoDId 生产订单明细资料ID
                    #endregion

                    #region 新加字段-2017-11-7-plf
                    mesOrder.CustomerCode = item["ccuscode"].ObjToString(); //客户编号
                    mesOrder.ScheduleDate = item["createdate"].ObjToDate().AddDays(1).ToString("yyyy-MM-dd hh:mm:ss"); //订单日期 
                    mesOrder.CreatedDate = headtable.Rows[0]["CreateDate"].ObjToDate().ToString("yyyy-MM-dd hh:mm:ss");  //创建日期
                    mesOrder.PlanStartDate = item["startdate"].ObjToDate().ToString("yyyy-MM-dd hh:mm:ss"); //计划开工日期 
                    mesOrder.PlanEndDate = item["duedate"].ObjToDate().ToString("yyyy-MM-dd hh:mm:ss"); //计划完工工日期 
                    mesOrder.RequireDate = item["dPreDate"].ObjToDate().ToString("yyyy-MM-dd hh:mm:ss"); //交货日期 --预发货日期 （u8）
                    mesOrder.SubQty = item["MrpQty"].ObjToDecimal(); //MrpQty Mrp净算量 
                    mesOrder.CustomerOrder = item["SoCode"].ObjToString(); //销售订单号(mes)--来源订单号(erp) 
                    mesOrder.Reserved2 = item["motypecode"].ObjToString(); //类型

                    #endregion

                    #region 新增自由项 jifeng

                    mesOrder.IsAutoInWh = "0";
                    #endregion

                    #region 新增字段 fulj 20180301
                    mesOrder.Define30 = item["Define30"].ObjToString();     //最终客户
                    mesOrder.OrderCode = item["OrderCode"].ObjToString();   //销售订单号
                    mesOrder.Cbdefine3 = item["cbdefine3"].ObjToString();   //客户最终订单号

                    #endregion
                #endregion
                    //子件信息
                    List<WorkOrderBomLinesItem> listBomLine = new List<WorkOrderBomLinesItem>();

                    DataTable dtBom = GetMoBom(item["MoDId"].ObjToInt32(), constr, accid);
                    if (dtBom != null && dtBom.Rows.Count > 0)
                    {
                        for (int i = 0; i < dtBom.Rows.Count; i++)
                        {
                            WorkOrderBomLinesItem BomLine = new WorkOrderBomLinesItem();
                            BomLine.BomRrn = dtBom.Rows[i]["AllocateId"].ObjToInt32();  //子件pk
                            BomLine.InvCode = dtBom.Rows[i]["InvCode"].ToString();      //物料编码
                            BomLine.LineMaxQty = dtBom.Rows[i]["Qty"].ObjToDecimal();   //需求数量
                            BomLine.UnitQty = dtBom.Rows[i]["Qtyb"].ObjToDecimal();    //单件用量
                            BomLine.StepName = dtBom.Rows[i]["OpCode"].ToString();       //工序编码
                            BomLine.MaterialSpec1 = dtBom.Rows[i]["cInvStd"].ObjToString(); //规格
                            BomLine.ProductType = dtBom.Rows[i]["ProductType"].ObjToInt32(); //产出类型(1:空/2:联产品/3:副产品)  
                            //BomLine.ByproductFlag = dtBom.Rows[i]["ByproductFlag"].ObjToInt32(); //是否联副产品 
                            listBomLine.Add(BomLine);
                        }
                    }
                    else
                    {
                        DebugWriteLog.WriteLine("生产订单接口", "table", " 子件没有主材");
                        throw new Exception("子件没有主材");
                    }
                    mesOrder.WorkOrderBomLines = listBomLine;
                    // DebugWriteLog.WriteLine("生产订单子件接口", "获取子件ID", listBomLine.ToJson());


                    mlist.Add(mesOrder);
                }

                //DebugWriteLog.WriteLine("生产订单接口", "获取订单表", mlist.ToJson());

                modids = modids.TrimEnd(',');

                #region 子件信息

                List<MesMoallocate> listmm = new List<MesMoallocate>();

                #endregion

                ApiRequest req = new ApiRequest();
                req.data = mlist;
                req.orgcode = accid;
                req.primarykey = key.ToString();
                req.operation = operation;

                DebugWriteLog.WriteLine("生产订单接口", "抛出参数", req.ToJson());
                return req.ToJson();
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 标准订单 存货分类01,06,08,09， 非标准订单，检查存货分类只有06,07
        /// </summary>
        /// <param name="modid"></param>
        /// <param name="moclass"></param>
        /// <param name="connstr"></param>
        /// <returns></returns>
        private bool checkMoabyMoclass(string modid, string moclass, string connstr)
        {
            string sql = "";
            if (moclass.Equals("1"))
            {
                sql = "select 1 from mom_moallocate a inner join inventory i on i.cinvcode = a.invcode where a.modid = " + modid + " and ( i.cinvccode like '01%' or i.cinvccode like '06%' or i.cinvccode like '08%' or i.cinvccode like '09%')";
            }
            else
            {
                sql = "select 1 from mom_moallocate a inner join inventory i on i.cinvcode = a.invcode where a.modid = " + modid + " and ( i.cinvccode like '06%' or i.cinvccode like '07%' )";
            }

            try
            {
                DataSet ds = DbHelperSQL.Query(sql, connstr);
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        public bool Update_After_sh(ref int moid, ref int modid, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            try
            {
                U8LoginInfo info = UFSoft.U8.Framework.ContextSrv.UserContextGetter.U8LoginInfo;
                UFSoft.U8.Framework.DBConnection.ConnectionCourier conier = UFSoft.U8.Framework.DBConnection.ConnectionCourier.Instance;
                constr = conier.GetCurrentConnection().ConnectionString;
                if (string.IsNullOrEmpty(constr))
                {
                    errMsg = "MoorderPlugin，Update_After，获取连接串失败";
                    DebugWriteLog.WriteLine("MoorderPlugin", "Update_After", errMsg);
                    return false;
                }
                string accid = info.UserAccountId;

                String js;

                js = GetCustJs_sh(accid, moid, modid, 0, 1);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }

                var result = HttpHelper.PostDataToServer(url, js);
                //UFIDA.U8.PUB.LogHelper.WriteApiLog(constr, info.UserName, "Mo", js, result);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    DebugWriteLog.WriteLine("MoorderPlugin", "Update_After", errMsg);
                    return false;
                }

                return true;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("MoorderPlugin", "Update_After", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }


        private DataTable GetMoBom(int modid, string constr, string accid)
        {
            #region 子件信息
            // inv.cInvStd 子件规格 
            //中欣晶元
            if (accid.Equals("010") || accid.Equals("020"))
            {
                var sqlzj = @"select d.AllocateId, d.MoDId,mo.MoCode,momd.SortSeq,d.SortSeq as bsortseq,d.OpSeq,d.Qty,d.ComponentId, d.InvCode,
                                d.Free1,d.Free2,d.Free3, d.BaseQtyN, d.BaseQtyD, convert(decimal(16,6), d.BaseQtyN / d.BaseQtyD ) as Qtyb ,
                                inv.cInvStd, d.ProductType , d.ByproductFlag,
                                op.OpCode, prd.[Description], momd.RoutingId, d.OpSeq,bo.Define22
                                from mom_moallocate d with (nolock)
                                inner join mom_orderdetail momd with (nolock) on d.MoDId=momd.MoDId
                                inner join mom_order mo with (nolock) on mo.MoId=momd.MoId
                                left join bom_opcomponent bo with (nolock) on bo.OpComponentId = d.OpComponentId 
                                left join sfc_prouting prp with (nolock) on prp.PRoutingId = momd.RoutingId 
                                left join sfc_proutingdetail prd with (nolock) on prd.PRoutingId = prp.PRoutingId and prd.OpSeq = d.OpSeq
                                left join sfc_operation op with (nolock) on op.OperationId = prd.OperationId
                                inner join Inventory inv with (nolock) on d.InvCode=inv.cInvCode
                                where inv.cinvccode like '1%' and d.MoDId in (" + modid + ")";


                //大和热磁
                //                var sqlzj = @"select d.AllocateId, d.MoDId,mo.MoCode,momd.SortSeq,d.SortSeq as bsortseq,d.OpSeq,d.Qty,d.ComponentId, d.InvCode,
                //                                   d.Free1,d.Free2,d.Free3, d.BaseQtyN, d.BaseQtyD, convert(decimal(16,6), d.BaseQtyN / d.BaseQtyD ) as Qtyb ,
                //                                    inv.cInvStd, d.ProductType , d.ByproductFlag,
                //                                   op.OpCode, prd.[Description], momd.RoutingId, d.OpSeq
                //                                   from mom_moallocate d
                //                                   left join mom_orderdetail momd on d.MoDId=momd.MoDId
                //                                   left join mom_order mo on mo.MoId=momd.MoId
                //                                   left join sfc_prouting prp on prp.PRoutingId = momd.RoutingId 
                //                                   left join sfc_proutingdetail prd on prd.PRoutingId = prp.PRoutingId and prd.OpSeq = d.OpSeq
                //                                   left join sfc_operation op on op.OperationId = prd.OperationId
                //                                   left join Inventory inv on d.InvCode=inv.cInvCode
                //                                   where d.MoDId in (" + modid + ")";
                DataTable tablezj = DbHelperSQL.Query(sqlzj, constr, null).Tables[0];
                return tablezj;
            }
            else // (accid.Equals("103") || accid.Equals("104"))
            {
                var sqlzj = @"select d.AllocateId, d.MoDId,mo.MoCode,momd.SortSeq,d.SortSeq as bsortseq,d.OpSeq,d.Qty,d.ComponentId, d.InvCode,
                                d.Free1,d.Free2,d.Free3, d.BaseQtyN, d.BaseQtyD, convert(decimal(16,6), d.BaseQtyN / d.BaseQtyD ) as Qtyb ,
                                inv.cInvStd, d.ProductType , d.ByproductFlag,
                                op.OpCode, prd.[Description], momd.RoutingId, d.OpSeq,bo.Define22 ,d.LotNo
                                from mom_moallocate d with (nolock)
                                inner join mom_orderdetail momd with (nolock) on d.MoDId=momd.MoDId
                                inner join mom_order mo with (nolock) on mo.MoId=momd.MoId
                                left join sfc_prouting prp with (nolock) on prp.PRoutingId = momd.RoutingId 
                                left join bom_opcomponent bo with (nolock) on bo.OpComponentId = d.OpComponentId 
                                left join sfc_proutingdetail prd with (nolock) on prd.PRoutingId = prp.PRoutingId and prd.OpSeq = d.OpSeq
                                left join sfc_operation op with (nolock) on op.OperationId = prd.OperationId
                                inner join Inventory inv with (nolock) on d.InvCode=inv.cInvCode
                                where  d.MoDId in (" + modid + ")";

                DataTable tablezj = DbHelperSQL.Query(sqlzj, constr, null).Tables[0];
                return tablezj;
            }
            #endregion
        }

        #region 暂时注释
        //public bool Update_After(ref int moid, ref int modid, ref string errMsg)
        //{
        //    //获取插件上下文
        //    bool bresult = true;
        //    try
        //    {
        //        MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;
        //        U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
        //        constr = login.UFDataConnstringForNet;

        //        #region 注释代码
        //        // U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
        //        // constr = login.UFDataConnstringForNet;
        //        //if (login != null)
        //        //{
        //        //    constr = login.UFDataConnstringForNet;
        //        //    HttpContext.Current.Session["login"] = login;
        //        //    DebugWriteLog.WriteLine("MoorderPlugin", "Update_After", "1:" + constr);
        //        //}
        //        //else
        //        //{
        //        //    login = HttpContext.Current.Session["login"] as clsLogin;
        //        //    constr = login.UFDataConnstringForNet;
        //        //    DebugWriteLog.WriteLine("MoorderPlugin", "Update_After", "2:" + constr);
        //        //} 
        //        #endregion

        //        String js;

        //        js = GetCustJs(login, moid, modid, 2);

        //        var result = HttpHelper.PostDataToServer(url, js);
        //        var apiresult = Common.DeserializeObject<ApiResponse>(result);
        //        if (apiresult.successful != 0)
        //        {
        //            errMsg = apiresult.message;
        //            //DebugWriteLog.WriteLine("MoorderPlugin", "Update_After", errMsg);
        //            return false;
        //        }

        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        DebugWriteLog.WriteLine("MoorderPlugin", "Update_After", ex);
        //        bresult = false;
        //        errMsg = ex.Message;
        //    }
        //    return true;
        //} 
        #endregion
        /*
        public bool Insert_After(ref int moid, ref int modid, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            try
            {
                MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

                //从上下文获取U8Login对象
                U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
                if (login != null)
                    constr = login.UFDataConnstringForNet;

                #region 注释代码
                //if (login != null)
                //{
                //    constr = login.UFDataConnstringForNet;
                //    HttpContext.Current.Session["login"] = login;
                //    DebugWriteLog.WriteLine("MoorderPlugin", "Update_After", "1:" + constr);
                //}
                //else
                //{
                //    login = HttpContext.Current.Session["login"] as clsLogin;
                //    constr = login.UFDataConnstringForNet;
                //    DebugWriteLog.WriteLine("MoorderPlugin", "Update_After", "2:" + constr);
                //} 
                #endregion

                String js;

                js = GetCustJs(login, moid, modid, 0);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("MoorderPlugin", "Insert_After", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }
         */

        public bool Delete_After(ref int moid, ref int modid, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            try
            {
                U8LoginInfo info = UFSoft.U8.Framework.ContextSrv.UserContextGetter.U8LoginInfo;
                UFSoft.U8.Framework.DBConnection.ConnectionCourier conier = UFSoft.U8.Framework.DBConnection.ConnectionCourier.Instance;
                constr = conier.GetCurrentConnection().ConnectionString;
                if (string.IsNullOrEmpty(constr))
                {
                    errMsg = "MoorderPlugin，Delte_After，获取连接串失败";
                    DebugWriteLog.WriteLine("MoorderPlugin", "Delte_After", errMsg);
                    return false;
                }
                string accid = info.UserAccountId;

                String js;
                js = GetCustJs(accid, moid, modid, 1, 1);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                DebugWriteLog.WriteLine("MoorderPlugin", "Delete_After", apiresult.ToJson());
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("MoorderPlugin", "Delete_After", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }
        public bool Delete_After_sh(ref int moid, ref int modid, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            try
            {
                U8LoginInfo info = UFSoft.U8.Framework.ContextSrv.UserContextGetter.U8LoginInfo;
                UFSoft.U8.Framework.DBConnection.ConnectionCourier conier = UFSoft.U8.Framework.DBConnection.ConnectionCourier.Instance;
                constr = conier.GetCurrentConnection().ConnectionString;
                if (string.IsNullOrEmpty(constr))
                {
                    errMsg = "MoorderPlugin，Delte_After，获取连接串失败";
                    DebugWriteLog.WriteLine("MoorderPlugin", "Delte_After", errMsg);
                    return false;
                }
                string accid = info.UserAccountId;

                String js;
                js = GetCustJs_sh(accid, moid, modid, 1, 1);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }
                var result = HttpHelper.PostDataToServer(url, js);
                //UFIDA.U8.PUB.LogHelper.WriteApiLog(constr, info.UserName, "Mo_Del", js, result);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                DebugWriteLog.WriteLine("MoorderPlugin", "Delete_After", apiresult.ToJson());
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("MoorderPlugin", "Delete_After", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }

        public bool Save_After(ref DataSet ds, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            try
            {
                MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;
                clsLogin login = ctx.U8Login as clsLogin;
                if (login != null)
                    constr = login.UFDataConnstringForNet;

                String js;

                DataTable dt = ds.Tables[0];
                //判断是否审核后修改 3

                DebugWriteLog.WriteLine("Save_After", "Save_After", "进入");

                string moid = dt.Rows[0]["moid"].ObjToString();
                string sql = "select * From mom_orderdetail where moid='" + moid + "'";
                DataSet dss = DbHelperSQL.Query(sql, login.UFDataConnstringForNet.ToString());
                DataTable  dtt= dss.Tables[0];
                int modid = dtt.Rows[0]["modid"].ObjToInt32();


                js = GetCustJs(login.get_cAcc_Id(), dt.Rows[0]["moid"].ObjToInt32(),modid, 0, 3);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }

                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    //DebugWriteLog.WriteLine("MoorderPlugin", "Update_After", errMsg);
                    return false;
                }

                return true;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("Save_After", "Save_After", "进入");
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }
     
        
    }
}